package com.fingard.dsp.bank.directbank.zjdsf01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.directbank.gzdsf01.util.CfbsAPI;
import com.fingard.dsp.bank.directbank.zjdsf01.util.StrSubstring;
import com.fingard.dsp.bank.directbank.zjdsf01.util.WMACREQ;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 浙江人行E户通(ZJDSF01)批量代收
 */
public class ZJDSF01BatPayRec extends ZJDSF01Base implements IBatPayRec {
	@Override
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
		return null;
	}

	@Override
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
		return null;
	}

	@Override
	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9188.reqHeader);
		retAts.reqSeqID = p_req9188.reqBatchNO;
		
		try {
			StringBuilder sbFileContent = new StringBuilder();
			
			/** 报文类型 */
			sbFileContent.append(ZJDSF01TransCode.BatRec_9188_918801);
			
			/** 服务类型 */
			sbFileContent.append("04");
			
			/** 发起方代码 */
			String corpNo = bankFront.corpNo;
			if (StringHelper.isNullOrEmpty(corpNo)) {
                retAts.respCode = "0";
                retAts.reqSeqID = p_req9188.reqBatchNO;
                retAts.respInfo = "发起方代码'corpNo'值为空,请检查BankFront.xml中ZJDSF01的<corpNo>标签配置值是否为空!";
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
			sbFileContent.append(String.format("%-10s", corpNo));
			
			/** 接收方代码 */
			String org = bankFront.org;
			if (StringHelper.isNullOrEmpty(org)) {
				retAts.respCode = "0";
				retAts.reqSeqID = p_req9188.reqBatchNO;
				retAts.respInfo = "接收方代码'org'值为空,请检查BankFront.xml中ZJDSF01的<org>标签配置值是否为空!";
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = FailCode.E9981;
				retAts.writeRetToATS();
				return retAts;
			}
			sbFileContent.append(String.format("%-10s", org));
			
			/** 本地日期 */
			sbFileContent.append(Format.Date8Format.format(p_req9188.getPayDateTime()));
			
			/** 本地时间 */
			sbFileContent.append(Format.Time6Format.format(p_req9188.getPayDateTime()));
			
			/** 回应码 */
			sbFileContent.append("99");
			
			/** 操作员代码 */
			String operator = bankFront.operator;
			if (StringHelper.isNullOrEmpty(operator)) {
				retAts.respCode = "0";
				retAts.reqSeqID = p_req9188.reqBatchNO;
				retAts.respInfo = "操作员代码'operator'值为空,请检查BankFront.xml中ZJDSF01的<operator>标签配置值是否为空!";
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = FailCode.E9981;
				retAts.writeRetToATS();
				return retAts;
			}
			sbFileContent.append(String.format("%-8s", operator));

			StringBuilder tmpSeqNoFileContent = new StringBuilder();
			while (p_req9188.readRecord()) {
				if (tmpSeqNoFileContent.length() > 0) {
					tmpSeqNoFileContent.append("\r\n");
				}
				
				StringBuilder macReqBuilder = new StringBuilder();
				
				/** 入网机构代码 */ 
				macReqBuilder.append(CfbsAPI.rightFill(corpNo, 10, " "));
				
				/** 提交日期 */
				macReqBuilder.append(Format.Date8Format.format(p_req9188.getPayDateTime()));
				
				/** 流水号 */
				String askNumber = p_req9188.readedDetail.askNumber;
				if (askNumber.length() > 8) {
					retAts.respCode = "0";
					retAts.reqSeqID = p_req9188.reqBatchNO;
					retAts.respInfo = "流水号长度过长，最长为8位，实际为:" + askNumber.length() + ",请设置流水号长度银行参数!";
					retAts.transState = PaymentState.FAIL_Batch;
					retAts.payInfoCode = FailCode.E9981;
					retAts.writeRetToATS();
					return retAts;
				}
				macReqBuilder.append(String.format("%8s", askNumber).replace(" ", "0"));
				tmpSeqNoFileContent.append(askNumber);
				
				/** 出帐银行号 */
				String cnapsCode = p_req9188.readedDetail.cnapsCode;
				if (StringHelper.isNullOrEmpty(cnapsCode)) {
					retAts.respCode = "0";
					retAts.reqSeqID = p_req9188.reqBatchNO;
					retAts.respInfo = "出账银行号'cnapsCode'值为空,请检查ATS明细字段中<CNAPSCode>节点值是否为空!";
					retAts.transState = PaymentState.FAIL_Batch;
					retAts.payInfoCode = FailCode.E9981;
					retAts.writeRetToATS();
					return retAts;
				}
				macReqBuilder.append(CfbsAPI.rightFill(cnapsCode, 10, " "));

				/** 付款人帐号 */
				macReqBuilder.append(CfbsAPI.rightFill(p_req9188.readedDetail.payAct, 30, " "));
				
				/** 付款人名称 */ 
				macReqBuilder.append(CfbsAPI.rightFill(p_req9188.readedDetail.payName, 60, " "));
				
				/** 入帐银行号 */
				String recBankNo = getBankConfig().getMapValueByKey("recCnapsCodeMapping", p_req9188.readedDetail.recAct);
				macReqBuilder.append(CfbsAPI.rightFill(recBankNo, 10, " "));
				
				/** 入帐帐号 */
				macReqBuilder.append(CfbsAPI.rightFill(p_req9188.readedDetail.recAct, 30, " "));
				
				/** 货币符号 */
				macReqBuilder.append("RMB");
				
				/** 金额 */
				macReqBuilder.append(String.format("%012d", Long.parseLong(StringHelper.amountMultiply100(p_req9188.readedDetail.payAmount))));
				
				/** 计量对象号码 */
				macReqBuilder.append(CfbsAPI.rightFill(p_req9188.readedDetail.customNo, 20, " "));
				
				/** 授权号 */ 
				macReqBuilder.append(CfbsAPI.rightFill(p_req9188.readedDetail.authCode, 12, " "));
				
				/** 支付工具类型 */
				/*0	未知
				1	活期储蓄存折
				2	对公账户 
				3	借记卡
				4	信用卡（贷记卡） 
				5	活期存款账户*/
				String cardType = p_req9188.readedDetail.cardType;
				if (StringHelper.hasAnyChar(cardType)) {
					if ("1".equals(cardType)) {
						cardType = "1";
					} else if ("2".equals(cardType)) {
						cardType = "3";
					} else if ("3".equals(cardType) || "4".equals(cardType)) {
						cardType = "4";
					}
				} else {
					cardType = "3";
				}
				if (!"1".equals(p_req9188.readedDetail.isPrivate)) {
					cardType = "2";
				}
				macReqBuilder.append(cardType);
				
				/** 凭证号码 */
				macReqBuilder.append(CfbsAPI.rightFill("", 16, " "));
				
				/** 附言 */
				macReqBuilder.append(CfbsAPI.rightFill("", 16, " "));
				
				/** 附加域子类 */
				macReqBuilder.append("49");
				
				/** 附加域长度 */
				macReqBuilder.append("041");
				
				String tmpEncryptMsg = macReqBuilder.toString();

				sbFileContent.append(tmpEncryptMsg);
				WriteBankLogLn2("当前明细生成mac前数据:\r\n" + tmpEncryptMsg);
				
				String tmpEncryptResult = WMACREQ.generateMac(tmpEncryptMsg, getCharset("batch"));
				WriteBankLogLn("当前明细mac码:" + tmpEncryptResult);
				
				/** 消息鉴别码 */
				sbFileContent.append(CfbsAPI.rightFill(tmpEncryptResult, 8, " "));
				
				/** 附加域内容 */
				sbFileContent.append(CfbsAPI.rightFill("", 41, " "));
			}
			WriteBankLogStep2(sbFileContent.toString());
			
			String tmpUploadFileName = "CMT031_" + p_req9188.reqBatchNO + ".z01";
			String tmpLocalMarkPath = getTempFileDirectory() + File.separator + tmpUploadFileName;
			WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);
			FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset("batch"));
			
			String tmpSeqNoFileData = tmpSeqNoFileContent.toString();
			WriteBankLogLn2("批次序号映射文件内容:\r\n" + tmpSeqNoFileData);
			String tmpSeqNoFilePath = getTempFileDirectory() + File.separator + p_req9188.reqBatchNO + ".txt";
			WriteBankLogLn2("批次序号文件保存本机路径: " + tmpSeqNoFilePath);
			FileHelper.writeFile(tmpSeqNoFilePath, tmpSeqNoFileData, getCharset("batch"));
			
			String[] tmpStrRet = sendBatchToBank(tmpLocalMarkPath, ZJDSF01TransCode.BatRec_9188_918801);
			
			if (tmpStrRet[0].length() == 0) {
				retAts.respCode = "0";
	            retAts.reqSeqID = p_req9188.reqBatchNO;
	            retAts.respInfo = "上传成功";
	        	retAts.transState = "Uploaded";
	        	retAts.payInfoCode = "I4001";
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "上传失败";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.toString();
			WriteBankLogLn(ex);
		}

		retAts.writeRetToATS();
		return retAts;
	}

	@Override
	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req9198.reqHeader);
		retAts.reqSeqID = p_req9198.reqBatchNO;
		
		try {
			String seqNoMappingContent = "";
			String tmpBatSeqNoPath = getTempFileDirectory(p_req9198.getBgnDateTime()) + File.separator + p_req9198.reqBatchNO + ".txt";
			WriteBankLogLn2("本地批量代收流水映射文件路径:" + tmpBatSeqNoPath);
			File tmpSeqNoMapDir = new File(tmpBatSeqNoPath);
			if (tmpSeqNoMapDir.exists()) {
				seqNoMappingContent = FileHelper.readToString(tmpSeqNoMapDir, getCharset("batch"));
				WriteBankLogLn2("本地批量代收流水映射文件内容:\r\n" + seqNoMappingContent);
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "本地未产生流水映射文件，未找到该批次记录!";
				retAts.writeAfterDetail();
				return retAts;
			}

			StringBuilder sbFileContent = new StringBuilder();
			
			/** 报文类型 */
			sbFileContent.append(ZJDSF01TransCode.BatRec_9198_918801);
			
			/** 服务类型 */
			sbFileContent.append("07");
			
			/** 发起方代码 */
			String corpNo = bankFront.corpNo;
			if (StringHelper.isNullOrEmpty(corpNo)) {
				retAts.respCode = "-1";
				retAts.respInfo = "发起方代码'corpNo'值为空,请检查BankFront.xml中ZJDSF01的<corpNo>标签配置值是否为空!";
				retAts.writeAfterDetail();
				return retAts;
			}
			sbFileContent.append(String.format("%-10s", corpNo));
			
			/** 接收方代码 */
			String org = bankFront.org;
			if (StringHelper.isNullOrEmpty(org)) {
				retAts.respCode = "-1";
				retAts.respInfo = "接收方代码'org'值为空,请检查BankFront.xml中ZJDSF01的<org>标签配置值是否为空!";
				retAts.writeAfterDetail();
				return retAts;
			}
			sbFileContent.append(String.format("%-10s", org));
			
			/** 本地日期 */
			sbFileContent.append(Format.Date8Format.format(new Date()));
			
			/** 本地时间 */
			sbFileContent.append(Format.Time6Format.format(new Date()));
			
			/** 回应码 */
			sbFileContent.append("99");
			
			/** 操作员代码 */
			String operator = bankFront.operator;
			if (StringHelper.isNullOrEmpty(operator)) {
				retAts.respCode = "-1";
				retAts.respInfo = "操作员代码'operator'值为空,请检查BankFront.xml中ZJDSF01的<operator>标签配置值是否为空!";
				retAts.writeAfterDetail();
				return retAts;
			}
			sbFileContent.append(String.format("%-8s", operator));

			StringBuilder macReqBuilder = new StringBuilder();
			
			/** 发起方代码 */ 
			macReqBuilder.append(CfbsAPI.rightFill(corpNo, 10, " "));
			
			/** 下载日期 */
			macReqBuilder.append(Format.Date8Format.format(p_req9198.getBgnDateTime()));
			
			/** 下载类型 */
			macReqBuilder.append("01");
			
			/** 本地日期 */
			macReqBuilder.append(Format.Date8Format.format(new Date()));
			
			/** 本地时间 */
			macReqBuilder.append(Format.Time6Format.format(new Date()));
			
			/** 操作员代码 */
			macReqBuilder.append(String.format("%-8s", operator));
			
			sbFileContent.append(macReqBuilder.toString());

            /** 消息鉴别码 */
            WriteBankLogLn2("当前明细生成mac前数据:\r\n" + macReqBuilder.toString());
            String tmpEncryptResult = WMACREQ.generateMac(macReqBuilder.toString(), getCharset("batch"));
            WriteBankLogLn("当前明细mac码:" + tmpEncryptResult);

			sbFileContent.append(CfbsAPI.rightFill(tmpEncryptResult, 8, " "));
			WriteBankLogStep2(sbFileContent.toString());
			
			String tmpUploadFileName = "DLD032" + p_req9198.reqBatchNO + ".z01";
			String tmpLocalMarkPath = getTempFileDirectory() + File.separator + tmpUploadFileName;
			WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);
			FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset("batch"));

			String[] tmpStrRet = sendBatchToBank(tmpLocalMarkPath, ZJDSF01TransCode.BatRec_9198_918801);

			if (tmpStrRet[0].length() == 0) {
				retAts.respCode = "0";
				
				String fileContent = tmpStrRet[1];
				String tmpRespCode = fileContent.substring(42, 44);
				if ("00".equals(tmpRespCode)) {
					String tmpRetStr = fileContent.substring(94);
					List<String> list = StrSubstring.getStrList(tmpRetStr, 257);
					Iterator<String> it = list.iterator();
					while(it.hasNext()) {
						String tmpDetailRecord = it.next();
						WriteBankLogLn("当前明细内容:" + tmpDetailRecord);
						String[] tmpSeqNoArray = seqNoMappingContent.split("\r\n");
						for (String tmpSeqNo : tmpSeqNoArray) {
							if (StringHelper.isNullOrEmpty(tmpSeqNo)) {
								continue;
							}
							String bankAskNumber = tmpDetailRecord.substring(18, 26);
							if (tmpSeqNo.equals(bankAskNumber)) {
								RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
								tmpRetDetail.payAct = tmpDetailRecord.substring(36,66).trim();
								tmpRetDetail.payName = new String(tmpDetailRecord.getBytes(getCharset("batch")), 66, 60, "GBK").trim();
								tmpRetDetail.postScript = tmpSeqNo;
								tmpRetDetail.payAmount = StringHelper.amountDivide100(new String(tmpDetailRecord.getBytes("GBK"), 169, 12, "GBK").trim());
								String result = new String(tmpDetailRecord.getBytes(getCharset("batch")), 254, 2, "GBK").trim();
								tmpRetDetail.result = tmpRespCode + "+" + result;
								tmpRetDetail.payInfoCode = result;
								retAts.writeRetDetail(tmpRetDetail);
							}
						}
					}
				} else {
					if ("03".equals(tmpRespCode)) {
						WriteBankLogLn("批次记录不存在");
						if (canBeNotExist(p_req9198, retAts, 45)) {
							retAts.respCode = "0";
							retAts.transState = tmpRespCode + "+" + tmpRespCode;
							retAts.payInfoCode = tmpRespCode;
							retAts.writeAfterDetail();
							return retAts;
						}
					} else {
						WriteBankLogLn("批次查询失败");
						retAts.respCode = "-1";
						retAts.respInfo = tmpRespCode;
					}
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeAfterDetail();
		return retAts;
	}
}